#!/usr/bin/env python
# -*- coding: utf-8 -*-

#   This file is part of pynix.

# Copyright (c) 2009 - Fabiano Francesconi, Walter Da Col

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

#TODO: Choerence in message: some include *, some variable ...

try:
    # Change the process name.
    import ctypes
    libc = ctypes.CDLL('libc.so.6')
    libc.prctl(15, 'pynix', 0, 0)
except:
    pass

from ConfigParser import MissingSectionHeaderError
import gettext
import paths
import __builtin__

import utils
from utils import *

import sys
import logging
import logging.handlers

import cfg_utils
from cfg_utils import ConfigurationFileDoesNotExist
from cfg_utils import ConfigurationFileSyntaxNotValid

from Cliparser import Parser

verbose = None
cfg_path = None
logger = None
configuration = None

def parse_options():
    ''' Parse CLI options '''
    global verbose, cfg_path
    
    # initialize parser
    parser = Parser()

    # initialize some parameters
    verbose = parser.is_verbose()
    cfg_path = parser.get_cfg_path()
    utils.set_use_color(parser.is_use_color())

def prepare_logger():
    ''' prepares and configures the logger '''
    global logger
    
    #initialize logger
    logger = logging.getLogger('Pynix Logger')
    logger.setLevel(logging.DEBUG)

    #prepare the path where log will be stored
    if (utils.is_running_as_root() == True):
        log_pathfilename = paths.ROOT_LOG_PATH + paths.ROOT_LOG_FILENAME
    else: #else if runned as normal user
        log_pathfilename = paths.USER_LOG_PATH + paths.USER_LOG_FILENAME

    ## if verbose option is specified, prepare a console handler too ##
    if (verbose == True):
        # create console handler and set level to debug
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)

        # create formatter for console
        formatter = logging.Formatter("%(message)s")

        # add formatter to ch
        ch.setFormatter(formatter)

        # add ch to logger
        logger.addHandler(ch)

    ## end of console handler

    # Add the log message handler to the logger

    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
    handler = logging.handlers.RotatingFileHandler(log_pathfilename, maxBytes=50000, backupCount=3)
    handler.setFormatter(formatter)

    logger.addHandler(handler)

    # rollover the logfile handler
    handler.doRollover()

    # logs a welcome message (:
    logger.info(green("* ")+_('Starting pynix')+green(" *"))


def initialize_environment():
    '''Constructor - Initialize environment'''
    
    global configuration, _
    ## load and install localization

    #TODO: Override default language
    # prepare environment for unicode usage

    try:
        __builtin__.__dict__['_'] = gettext.translation('pynix', paths.LANG_PATH).ugettext
    except IOError:
        __builtin__.__dict__['_'] = gettext.translation('pynix', fallback=True).ugettext

    ## get options from CLI
    parse_options()

    ## prepare the logger
    prepare_logger()

    ## get configuration
    try:
        configuration = cfg_utils.get_configuration(cfg_path)
    except ConfigurationFileDoesNotExist, error:
        logger.error(red(_("Configuration file cannot be found."))+"\n%(error)s" % {'error': error})
        quit(1)
    except MissingSectionHeaderError, error:
        logger.error(red(_("A section is missing from the configuration file:"))+"\n%(error)s" % {'error': error})
        quit(1)
    except ConfigurationFileSyntaxNotValid:
        #FIXME: transalte error message
        logger.error(red(_("Configuration file syntax showed some errors. Unable to continue executing pynix")))
        quit(1)

    ## set language to the one provided in the configuration file
    newlang = configuration["General"]["language"]
    logger.info(cyan(">> ")+_("Switching application language to %(language)s" % {'language': newlang}))
    __builtin__.__dict__['_'] = gettext.translation('pynix', paths.LANG_PATH,languages=[newlang], fallback=True).ugettext
    logger.info(green(" !- [ OK ]\n"))

def run():
    if (configuration):
        print "Backup → Destination:", configuration["Backup"]["destination"]
    quit(0)

def quit(status):
    if (status == 0):
        logger.info(green("* ")+_('All operations completed successfully')+green(" *"))
    elif (status == 1):
        logger.error(red("* "+_("Terminating pynix with error(s)")+red(" *")))
    logging.shutdown()
    sys.exit(status)

def main():
    initialize_environment()
    run()

if __name__ == '__main__':
    main()
